package com.imooc.security.core.social;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.security.SpringSocialConfigurer;

/**
 * Social配置
 * @author JZH
 *
 */
@EnableSocial
@Configuration
public class SocialConfig extends SocialConfigurerAdapter{

	@Autowired
	private DataSource dataSource;
	
	/**
	 * 设置存储connector的jdbs数据源
	 */
	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		// TODO Auto-generated method stub
		
		/**
		 * textEncryptor：加解密
		 */
		JdbcUsersConnectionRepository jdbcUsersConnectionRepository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
		jdbcUsersConnectionRepository.setTablePrefix("imooc_"); //表明只能是userconnection，但是可以加前缀
		return jdbcUsersConnectionRepository;
	}
	
	/*
	 * userconnection的脚本：
		-- This SQL contains a "create table" that can be used to create a table that JdbcUsersConnectionRepository can persist
		-- connection in. It is, however, not to be assumed to be production-ready, all-purpose SQL. It is merely representative
		-- of the kind of table that JdbcUsersConnectionRepository works with. The table and column names, as well as the general
		-- column types, are what is important. Specific column types and sizes that work may vary across database vendors and
		-- the required sizes may vary across API providers. 
		
		create table UserConnection (userId varchar(255) not null,
			provideruserconnectionId varchar(255) not null,
			providerUserId varchar(255),
			rank int not null,
			displayName varchar(255),
			profileUrl varchar(512),
			imageUrl varchar(512),
			accessToken varchar(512) not null,
			secret varchar(512),
			refreshToken varchar(512),
			expireTime bigint,
			primary key (userId, providerId, providerUserId));
		create unique index UserConnectionRank on UserConnection(userId, providerId, rank);
	 */
	
	
	
	/**
	 * 支持社交登陆方式的配置类
	 * @return
	 */
	@Bean
	public SpringSocialConfigurer imoocSocialSecurityConfig() {
		return new SpringSocialConfigurer();
	}
	
}
